import os, sys, time, signal
import serial  # 导入模块 # 安装：pip install pyserial 
from xmodem import XMODEM

from modem import YMODEM

from comm_serial import *

import serial.tools.list_ports

def recv_xmodem(ser, filename):
    def getc(size,timeout=8):
        time_limit = time.time() + timeout
        while time.time() < time_limit:
            gbytes = ser.read(size)
            if gbytes:
                #print(f'->R: {gbytes}')
                return gbytes
        return  None
    def putc(data,timeout=8):
        # self.textBrowser.append('#')
        #print(f'->S: {data}')
        pbytes = ser.write(data)
        return pbytes or None
    modem = YMODEM(getc, putc)

    try:
        print("Waiting for YMODEM transfer...")
        status = modem.recv(filename)
        print("File received successfully.")
    except:
        print(f'receive error: {status}')
        print("File received error!")
        return

    return

def waiting_str(serial, retstr,timeout):
    end_time = time.time() + timeout
    
    while time.time() < end_time:
        serial.send_cmd("")
        time.sleep(0.1)
        rcv = serial.read_all()
        print(rcv)
        if retstr in rcv:
            return
        time.sleep(0.1)
        if end_time <= time.time():
            print("串口异常", "请检查串口连接")
            raise Exception("shell timeout")

def get_picture_process(port):
    '''send command G to west, get one picture.
    '''
    deviceread="Device ready"
    serial = CommSerial(port, baudrate=115200)
    if not serial.isOpen():
        return
    print("Do get_picture_process.")
    try:
        waiting_str(serial, deviceread, 60)
    except:
        print("Error device is not ready!")
        return None
    # Send command G
    serial.send_cmd("G")
    # wait for get picture finished
    try:
        waiting_str(serial, "get picture finished", 60)
    except:
        print("Get picture time out")
        return None
    # 开始接收文件
    file_path='./recdata'  # 指定接收文件的路径和名称

    recv_xmodem(serial, file_path)

    # 关闭串行连接
    serial.close()

def send_picture_process(port):
    '''Do command U for send picture data to west.
    '''
    print("Do send_picture_process.")

def do_calculate_process(port):
    '''Command V: Calculate.
    '''
    print("Do do_calculate_process.")

def main(argv):
    if len(argv) < 3:
        return
    
    if len(argv) == 3:
        if argv[2] == 'G':
            # get one picture
            get_picture_process(argv[1])
            return
        elif argv[2] == 'U':
            send_picture_process(argv[1])
            return
        elif argv[2] == 'V':
            do_calculate_process(argv[1])
            return
    print("Environment Variables:")



#......
if __name__ == '__main__':
    print(f"Arguments count:{len(sys.argv)}")
    for i, arg in enumerate(sys.argv):
        print(f"Argument: {i:>6}: {arg}")
    main(sys.argv)










